
// 学生选修课程
import {Course, CourseSelection, Res} from "../types";
import {deleteRequest, error, getRequest, ok, postRequest, putRequest } from "../utils/myAxios.ts";
import {getCourseById} from "./CourseApi.ts";

//查询课程选修列表
export async function getCourseSelectionList(departmentId:string,courseId:string,studentId:string): Promise<Res<Array<CourseSelection>>> {
    let url = `/course-selection?`;
    let urlParams = new URLSearchParams();
    if (departmentId){
        urlParams.set('departmentId', departmentId)
    }
    if (courseId){
        urlParams.set('courseId', courseId)
    }
    if (studentId){
        urlParams.set('studentId', studentId)
    }
    const list = await getRequest<Array<CourseSelection>>(url + urlParams.toString());
    console.log('获取课程选修列表', list);
    if (list?.length >= 0) {
        return ok(list, 'ok');
    } else {
        return error([], "请求失败，请重试");
    }
}

//获取课程下当前选修人数
export async function getCourseSelectionCount(courseId: string,departmentId:string): Res<number> {
    let url = '/course-selection?';
    let urlParams = new URLSearchParams();
    if (departmentId){
        urlParams.set('departmentId', departmentId);
    }
    if (courseId){
        urlParams.set('courseId', courseId);
    }
    const res = await getRequest<CourseSelection[]>(url + urlParams.toString())
    if (res?.length >= 0) {
        return ok(res.length, 'ok');
    } else {
        return error(0, "请求失败，请重试");
    }
}

//查询是否选修
export async function getIsSelectionCourse(courseId: string,departmentId:string,studentId:string): Res<boolean> {
    const res = await getCourseSelectionList(departmentId, courseId, studentId)
    if (res.data.length > 0){
        return ok(true, '已经选修')
    }else{
        return ok(false, '未选修')
    }
}

// 添加课程选修信息
export async function addCourseSelection(courseSelection: CourseSelection): Promise<Res<CourseSelection>> {
    const res = await getCourseSelectionList(courseSelection.departmentId, courseSelection.courseId, courseSelection.studentId)
    if (res.data.length !== 0){
        return error({}, '已经选修')
    }
    //查询课程信息
    const courseRes = await getCourseById(courseSelection.courseId)
    //查询课程时间是否冲突
    const courseSelectRes = await getCourseSelectionList( courseSelection.departmentId, undefined, courseSelection.studentId)
    for (let i = 0; i < courseSelectRes.data.length; i++) {
        //查询已经选择的课程
        const assingmentCourseRes = await getCourseById(courseSelectRes.data[i].courseId)
        console.log('星期判断',courseRes.data.xq, assingmentCourseRes.data.xq)
        if (courseRes.data.xq === assingmentCourseRes.data.xq){
            //判断上课范围是否冲突
            if (isOverlap([courseRes.data.start, courseRes.data.end],
                [assingmentCourseRes.data.start, assingmentCourseRes.data.end])){
                return error({}, `与${assingmentCourseRes.data.name}课程时间冲突`)
            }

        }

    }

    const r = await postRequest<CourseSelection>(`/course-selection`, courseSelection);
    console.log('添加课程选修res：', r);
    if (r.id) {
        return ok(r, '添加成功');
    } else {
        return error(r);
    }
}

// 更新课程选修信息
export async function updateCourseSelection(courseSelection: CourseSelection): Promise<Res<CourseSelection>> {
    const r = await putRequest<CourseSelection>(`/course-selection/${courseSelection.id}`, courseSelection);
    console.log('更新课程选修res：', r);
    if (r.id) {
        return ok(r, '更新成功');
    } else {
        return error(r);
    }
}

function isOverlap(timeRange1, timeRange2) {
    const [start1, end1] = timeRange1;
    const [start2, end2] = timeRange2;
    // 如果一个时间段在另一个时间段之前，则它们没有交集
    if (end1< start2) {
        return false;
    }
    // 如果一个时间段在另一个时间段之后，则它们没有交集
    if (end2< start1) {
        return false;
    }
    // 否则，两个时间段有交集
    return true;
}


export async function deleteCourseSelection(courseSelection: CourseSelection): Res<CourseSelection> {

    const r = await getCourseSelectionList(courseSelection.departmentId, courseSelection.courseId, courseSelection.studentId)
    if (r.data.length === 0){
        return error({}, '未找到对应选修数据')
    }
    if (r.data.length === 1){
        const res = await deleteRequest<CourseSelection>(`/course-selection/${r.data[0].id}`);
        console.log('删除课程选修res：', r);
        if (res.id) {
            return ok(r, '删除成功');
        } else {
            return error(r, '删除失败');
        }
    }
    return error(r, '发现多条重复数据 请手动处理');

}

// 删除课程选修
export async function deleteCourseSelectionById(id: string):Res<CourseSelection> {
    const r = await deleteRequest<CourseSelection>(`/course-selection/${id}`);
    console.log('删除课程选修res：', r);
    if (r.id) {
        return ok(r, '删除成功');
    } else {
        return error(r);
    }
}

// 查询单个课程选修详情
export async function getCourseSelectionById(id: string): Promise<Res<CourseSelection>> {
    const r = await getRequest<CourseSelection>(`/course-selection/${id}`);
    console.log('查询课程选修res：', r);
    if (r.id) {
        return ok(r, '查询成功');
    } else {
        return error(r);
    }
}
